package com.atguigu.controller;

import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * Date:2022/11/5
 * Author:ybc
 * Description:
 */
@Controller
@RequestMapping("/houseImage")
public class HouseImageController {

    @DubboReference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId, @PathVariable Integer type, Model model){
        model.addAttribute("houseId", houseId);
        model.addAttribute("type", type);
        return "house/upload";
    }

    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(
            @PathVariable Long houseId,
            @PathVariable Integer type,
            @RequestParam("file") MultipartFile[] files
    ) throws IOException {
        if(files.length > 0){
            for (MultipartFile file : files) {
                //获取文件名
                String fileName = file.getOriginalFilename();
                //获取文件的后缀名
                String hzName = fileName.substring(fileName.lastIndexOf("."));
                //使用UUID作为新的文件名
                String uuid = UUID.randomUUID().toString();
                fileName = uuid + hzName;
                //上传文件
                QiniuUtil.upload2Qiniu(file.getBytes(), fileName);
                //创建HouseImage对象
                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setImageName(fileName);
                houseImage.setImageUrl("http://rkyesodbp.hn-bkt.clouddn.com/"+fileName);
                houseImage.setType(type);
                //将图片添加到数据库
                houseImageService.save(houseImage);
            }
        }
        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId, @PathVariable Long id){
        //通过id查询图片的信息
        HouseImage houseImage = houseImageService.getById(id);
        //将图片从七牛云中删除
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageName());
        //从数据库中将图片删除
        houseImageService.delete(id);
        return "redirect:/house/"+houseId;
    }

}
